package com.duo.advice;

import com.duo.enums.errorcode.BaseCode;
import com.duo.exception.BaseException;
import com.duo.result.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

    @ExceptionHandler(BaseException.class)
    public BaseResult baseExceptionHandler(BaseException e) {
        log.error(e.getMessage(), e);
        return new BaseResult(e.getCode(), e.getMsg(), e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public BaseResult methodArgumentNotValidExceptionHandler(BindException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        FieldError fieldError = (FieldError) objectError;
        return new BaseResult(BaseCode.ParameterValueError, fieldError.getField() + " " +objectError.getDefaultMessage());
    }

    @ExceptionHandler(Exception.class)
    public BaseResult baseExceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return new BaseResult(BaseCode.InnerError.getCode(), BaseCode.InnerError.getMessage(), e.getMessage());
    }
}
